package hos.thread.lifecycle

import android.annotation.SuppressLint
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import hos.map.FastSafeMap
import hos.thread.ThreadOption
import hos.thread.hander.MainHandler

/**
 * <p>Title: LifecycleHandler </p>
 * <p>Description: 感知生命周期的Handler </p>
 * <p>Company: www.mapuni.com </p>
 *
 * @author : 蔡俊峰
 * @date : 2023/8/3 8:56
 * @version : 1.0
 */
@SuppressLint("RestrictedApi")
class LifecycleHandler private constructor(
    private val lifecycleOwner: LifecycleOwner,
) : MainHandler() {

    companion object {

        @JvmStatic
        private val observerMap by lazy { FastSafeMap<LifecycleOwner, LifecycleHandler>() }

        @JvmStatic
        @JvmOverloads
        fun runLifecycle(
            lifecycleOwner: LifecycleOwner,
            handle: ThreadOption.UI = ThreadOption.UI.ON,
            time: Long = 400,
            block: MainHandler.() -> Unit,
        ) = getLifecycle(lifecycleOwner).start(handle, time, block)


        @JvmStatic
        fun getLifecycle(
            lifecycleOwner: LifecycleOwner,
        ): LifecycleHandler {
            val value = observerMap.getValue(lifecycleOwner)
            if (value != null) return value
            val lifecycleHandler = LifecycleHandler(lifecycleOwner)
            val previous = observerMap.putIfAbsent(lifecycleOwner, lifecycleHandler)
            if (previous != null) {
                // 已经存在
                return previous
            }
            // 不存在，返回新的
            return lifecycleHandler
        }

    }

    init {

        val lifecycleEventObserver = object : LifecycleEventObserver {
            override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
                if (event == Lifecycle.Event.ON_DESTROY) {
                    // 页面销毁的时候
                    clearCallback()
                    // 移除生命周期监听
                    lifecycleOwner.lifecycle.removeObserver(this)
                    Log.d("Lifecycle", "LifecycleHandler onDestroy: ${observerMap.size()}")
                    // 移除当前的Handler
                    observerMap.remove(lifecycleOwner)
                    Log.d("Lifecycle", "LifecycleHandler onDestroy: ${observerMap.size()}")
                }
            }
        }
        if (isMainThread()) {
            lifecycleOwner.lifecycle.addObserver(lifecycleEventObserver)
        } else {
            post {
                lifecycleOwner.lifecycle.addObserver(lifecycleEventObserver)
            }
        }
    }

}